/*
 * The MIT License
 *
 * Copyright (c) 2013-2016 reark project contributors
 *
 * https://github.com/reark/reark/graphs/contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package io.reark.rxgithubapp.advanced.slice;

import com.bumptech.glide.Glide;
import io.reark.reark.utils.Log;
import io.reark.rxgithubapp.ResourceTable;
import io.reark.rxgithubapp.advanced.data.DbUtils;
import io.reark.rxgithubapp.advanced.data.UserSettings;
import io.reark.rxgithubapp.shared.network.NetworkApi;
import io.reark.rxgithubapp.shared.pojo.GitHubRepository;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.io.IOException;

/**
 * MainAbility.
 *
 * @since 2021-08-06
 */
public class RepositorySlice extends AbilitySlice {
    private static final int DEFAULT_REPOSITORY_ID = 15491874;
    private static final String TAG = "RepositorySlice";
    Button button;
    private Text titleTextView;
    private Text stargazersTextView;
    private Text forksTextView;
    private Image avatarImageView;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_repository);
        titleTextView = (Text) findComponentById(ResourceTable.Id_widget_layout_title);
        stargazersTextView = (Text) findComponentById(ResourceTable.Id_widget_layout_stargazers);
        forksTextView = (Text) findComponentById(ResourceTable.Id_widget_layout_forks);
        avatarImageView = (Image) findComponentById(ResourceTable.Id_widget_avatar_image_view_1);
        button = (Button) findComponentById(ResourceTable.Id_repository_fragment_choose_repository_button);
        button.setClickedListener(component -> {
            present(new RepositoriesSlice(), new Intent());
        });
        if (intent.hasParameter("data")) {
            GitHubRepository repository = intent.getSerializableParam("data");
            titleTextView.setText(repository.getName());
            stargazersTextView.setText("stars: " + repository.getStargazersCount());
            forksTextView.setText("forks: " + repository.getForksCount());

            Glide.with(getContext())
                    .load(repository.getOwner().getAvatarUrl())
                    .fitCenter()
                    .into(avatarImageView);

            UserSettings userSettings = new UserSettings();
            userSettings.setId((long) repository.getId());
            userSettings.setName(repository.getName());
            userSettings.setStargazersCount(repository.getStargazersCount());
            userSettings.setForksCount(repository.getForksCount());
            userSettings.setAvatarUrl(repository.getOwner().getAvatarUrl());
            DbUtils.setWidget(userSettings, this);
        } else {
            UserSettings userSettings = DbUtils.getWidget(this);
            if (!userSettings.getName().equals("")) {
                titleTextView.setText(userSettings.getName());
                stargazersTextView.setText("stars: " + userSettings.getStargazersCount());
                forksTextView.setText("forks: " + userSettings.getForksCount());
                Glide.with(getContext())
                        .load(userSettings.getAvatarUrl())
                        .fitCenter()
                        .skipMemoryCache(true)
                        .into(avatarImageView);
                return;
            }
            String baseUrl = "";
            try {
                baseUrl =  getResourceManager().getElement(io.reark.rxgithubapp.shared.ResourceTable.String_base_url).getString();
            } catch (IOException | NotExistException | WrongTypeException e) {
                Log.d(TAG,e.getMessage());
            }
            Call<GitHubRepository> s =new NetworkApi(baseUrl).getRepository(DEFAULT_REPOSITORY_ID);
            s.enqueue(new Callback<GitHubRepository>() {
                @Override
                public void onResponse(Call<GitHubRepository> call, Response<GitHubRepository> response) {
                    GitHubRepository repository = response.body();

                    titleTextView.setText(repository.getName());
                    stargazersTextView.setText("stars: " + repository.getStargazersCount());
                    forksTextView.setText("forks: " + repository.getForksCount());
                    Glide.with(getContext())
                            .load(repository.getOwner().getAvatarUrl())
                            .fitCenter()
                            .skipMemoryCache(true)
                            .into(avatarImageView);

                    UserSettings userSettings = new UserSettings();
                    userSettings.setId((long) repository.getId());
                    userSettings.setName(repository.getName());
                    userSettings.setStargazersCount(repository.getStargazersCount());
                    userSettings.setForksCount(repository.getForksCount());
                    userSettings.setAvatarUrl(repository.getOwner().getAvatarUrl());
                    DbUtils.setWidget(userSettings, getContext());
                }

                @Override
                public void onFailure(Call<GitHubRepository> call, Throwable throwable) {

                }
            });
        }
    }


    @Override
    protected void onActive() {
        super.onActive();
    }


}
